from comment.comviews import *
from utils.dbutils import DB_Config, MysqlTools
from utils.tokens import *
from .sqlmap import *
from django.http import HttpResponse
import json
from user_agents import parse

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))


@format_response
def index(request):
    active = request.GET.get("active")
    body = json.loads(request.body.decode())
    time = body.get("time")
    params = body.get("params")
    if isinstance(params, str):
        params = json.loads(params)
    appInfo = body.get("appInfo")
    if not all([time, params, appInfo]):
        return err_response(311, "签名错误")
    if active == "quit":  # 退出
        uid = body.get("uid")
        cache.delete(uid)
        return success_response()
    elif active == "login":
        sql = TaskSqlMap.login.format(**params)
        result = mysql_tools.select_one(sql)
        if not result:
            return err_response(311, "用户名或密码错误")
        if isinstance(result,JsonResponse):
            return result
        # login success
        username = params.get("name")
        password = params.get("password")
        if not all([username, password]):
            return err_response(311)
        token = create_token(params["name"], params["password"])
        HTTP_USER_AGENT = request.META.get('HTTP_USER_AGENT', None)
        real_ip = get_ip(request)
        log = {}
        agent = parse(HTTP_USER_AGENT)
        log["browser"] = agent.browser.family + "/" + agent.browser.version_string
        log["ip_addr"] = real_ip
        log["login_time"] = "now()"
        log["session_id"] = ""
        log["user_id"] = result.get("user_id")
        logging.error(log)
        sql_login_record = TaskSqlMap.login_log.format(**log)
        mysql_tools.execute_sql(sql_login_record, commit=True)
        sql_user = TaskSqlMap.update_last_ip.format(
            **{"ip_addr": real_ip, "login_time": "now()", "user_id": result["user_id"]})
        mysql_tools.execute_sql(sql_user, commit=True)
        dict = {}
        dict["token"] = token
        dict["user_id"] = result.get("user_id")
        dict["role_value"] = result.get("role_value")
        return success_response(dict)
